/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.runtime;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件读取工具
 */
@Slf4j
public class FileOperator {

    /**
     * 读取yaml文件解析为MAP
     *
     * @param filePath
     * @return
     */
    public static Map<String, Object> getYaml(String filePath) {
        Map<String, Object> yamlContent = new HashMap<>();
        File yamlFile = new File(filePath);
        InputStream input = null;
        if (yamlFile.exists()) {
            try {
                input = new FileInputStream(yamlFile);
                Yaml yaml = new Yaml();
                yamlContent = yaml.load(input);

                //从yaml中获取到相关配置
                if (yamlContent.containsKey("msu-config")) {

                }
            } catch (Throwable e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                } catch (Throwable e) {
                    throw new RuntimeException("Close InputStream Error", e);
                }
            }
        }
        return yamlContent;
    }

    /**
     * 读取文本文件内容
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static String readToBuffer(String filePath) {
        StringBuffer buffer = new StringBuffer();
        try {
            InputStream stream = null;
            BufferedReader reader = null;
            try {
                File file = new File(filePath);
                if (!file.exists())
                    return null;
                stream = new FileInputStream(file);
                String line; // 用来保存每行读取的内容
                reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
                line = reader.readLine(); // 读取第一行
                while (line != null) { // 如果 line 为空说明读完了
                    buffer.append(line); // 将读到的内容添加到 buffer 中
                    buffer.append("\n"); // 添加换行符
                    line = reader.readLine(); // 读取下一行
                }
            } finally {
                if (reader != null)
                    reader.close();
                if (stream != null)
                    stream.close();
            }
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
        return buffer.toString();
    }

    /**
     * 保存文件
     *
     * @param str
     * @param filePath
     */
    public static void saveNewFile(String str, String filePath) {
        try {
            File f = new File(filePath);
            //父目录不存在建立目录
            if (f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            //如果已存在删除文件
            if (f.exists()) {
                f.delete();
            }
            f.createNewFile();

            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f));
            BufferedWriter writer = new BufferedWriter(write);
            writer.write(str);
            writer.flush();
            write.close();
            writer.close();
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
    }

    public static String toYaml(Object object){
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        mapper.findAndRegisterModules();
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER));
        StringWriter stringWriter = new StringWriter();
        try {mapper.writeValue(stringWriter, object);
            return stringWriter.toString();
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public static <T> T toObject(String yamlStr, Class<T> clazz){
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        mapper.findAndRegisterModules();
        try {
            return mapper.readValue(yamlStr, clazz);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }
}
